// ==UserScript==
// @name         Network Activity Logger
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Manage and download network activity logs
// @run-at       document-start
// ==/UserScript==

(function() {
    'use strict';
    // 用于存储网络活动日志的键
    const NETWORK_ACTIVITY_LOG_KEY = 'networkActivityLog';

    window.printNetworkActivityLog = function() {
        const logData = getNetworkActivityLog();
        console.log('Network Activity Log:', logData);
    };

    window.clearNetworkActivityLog = function() {
        setNetworkActivityLog({});  // 设置空对象来清空日志
        console.log('Network Activity Log has been cleared.');
    };

    // 定义一个函数来安全地存储复杂对象
    window.setNetworkActivityLog = function (logData) {
        const serializableLogData = JSON.stringify(logData);
        try {
            localStorage.setItem(NETWORK_ACTIVITY_LOG_KEY, serializableLogData);
        } catch (e) {
            if (e instanceof DOMException && e.code === DOMException.QUOTA_EXCEEDED_ERR) {
                msg = 'LocalStorage capacity exceeded'
                console.error(msg);
                // 处理存储空间不足的情况
                alert(msg)
            }
        }
    }

    // 定义一个函数来安全地读取复杂对象
    window.getNetworkActivityLog = function () {
        const logDataStr = localStorage.getItem(NETWORK_ACTIVITY_LOG_KEY, '{}');
        return JSON.parse(logDataStr);
    }

    // 定义一个函数来下载网络活动日志
    window.downloadNetworkActivityLog = function () {
        const logData = getNetworkActivityLog();
        const dataStr = JSON.stringify(logData, null, 2);
        const blob = new Blob([dataStr], { type: "application/json" });
        const url = URL.createObjectURL(blob);

        const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
        const hostname = location.hostname;
        const pathname = location.pathname.replace(/\//g, '_');
        const filename = `networkActivityLog-${hostname}${pathname}-${timestamp}.json`;

        const downloadAnchorNode = document.createElement('a');
        downloadAnchorNode.setAttribute('href', url);
        downloadAnchorNode.setAttribute('download', filename);
        document.body.appendChild(downloadAnchorNode);
        downloadAnchorNode.click();
        downloadAnchorNode.remove();
    }


  window.getLocalStorageSize = function() {
      let totalBytes = 0;
      for (let key in localStorage) {
          if (localStorage.hasOwnProperty(key)) {
              const currentKeySize = key.length + localStorage[key].length;
              totalBytes += currentKeySize;
          }
      }

      const totalKilobytes = totalBytes / 1024;
      const totalMegabytes = totalKilobytes / 1024;
      const maxSizeMegabytes = 5; // 大多数浏览器的 localStorage 限制为 5MB
      const remainingMegabytes = maxSizeMegabytes - totalMegabytes;


      return {
          totalKilobytes: totalKilobytes.toFixed(5),
          totalMegabytes: totalMegabytes.toFixed(5),
          remainingMegabytes: remainingMegabytes.toFixed(2),
          maxSizeMegabytes: maxSizeMegabytes
      };
  }




})();